<?php
/*
 表的结构
 CREATE TABLE `t_sessions` ( 
  `id` varchar(255) binary NOT NULL default '', 
  `expires` int(10) unsigned NOT NULL default '0', 
  `data` text, 
  PRIMARY KEY  (`id`) 
) TYPE=InnoDB; 
*/
class Session extends Model { 
   //Session的有效期
   public $lifeTime;
   protected $tbName = "sessions";
   
   //保存Session到什么地方. “db”：到数据库， "file":到文件
   public $saveTo = "db";
   
   function open($savePath, $sessName) { 
   	   // get session-lifetime 
       $this->lifeTime = get_cfg_var("session.gc_maxlifetime");
       return true; 
   } 
   
   function close() { 
       $this->gc(ini_get('session.gc_maxlifetime')); 
       // close database-connection 
       return @mysql_close($this->dbHandle); 
   } 
   function read($sessID) { 
       $data = $this->be($sessID); 
       return $data['expires'] > time() ? $data['data'] : ""; 
   }
   function write($sessID,$sessData) { 
       // new session-expire-time 
       $newExp = time() + $this->lifeTime; 

       $data['id'] = $sessID;
       $data['expires'] = $newExp;
       $data['data'] = $sessData;
       
       $this->replace($data);
       // if something happened, return true 
       if($this->db->affectedRows()){
       		return true; 
       }
       return false; 
   } 
   function destroy($sessID) { 
   		$this->remove($sessID);
   		
       if($this->db->affectedRows()){
       	   return true; 
       }
       return false; 
   }
   
   //garbage collection routine 
   function gc($sessMaxLifeTime) { 
   		$this->removeByCondition("WHERE expires < ".time());
        return $this->db->affectedRows(); 
   } 
}